/**
 * Project Name:template-web
 * File Name   :CustomSimpleMappingExceptionResolver.java
 * Package Name:org.cn.template.component.web.resolver
 * Date:2015年9月27日下午4:53:17
 * Copyright (c) 2015, http://my.oschina.net/httpssl All Rights Reserved.
 *
*/

package org.cn.template.component.web.resolver;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

/**
 * ClassName:CustomSimpleMappingExceptionResolver <br/>
 * Function :TODO ADD FUNCTION. <br/>
 * Reason	:TODO ADD REASON. <br/>
 * Date     :2015年9月27日 下午4:53:17 <br/>
 * @author  :http://my.oschina.net/httpssl
 * @email   :491835898@QQ.COM
 * @since   :JDK 1.7
 * @see 	 
 */
public class CustomSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {

	public static final String AJAX_ACCEPT = "accept";
	public static final String AJAX_application_json = "application/json";

	public static final String AJAX_X_Requested = "X-Requested-With";

	public static final String AJAX_XMLHttpRequest = "XMLHttpRequest";

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		// Expose ModelAndView for chosen error view.
		String viewName = determineViewName(ex, request);
		if (viewName != null) {// JSP格式返回
			if (!(request.getHeader(AJAX_ACCEPT).indexOf(AJAX_application_json) > -1
					|| (request.getHeader(AJAX_X_Requested) != null
							&& request.getHeader(AJAX_X_Requested).indexOf(AJAX_XMLHttpRequest) > -1))) {
				// 如果不是异步请求
				// Apply HTTP status code for error views, if specified.
				// Only apply it if we're processing a top-level request.
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				return getModelAndView(viewName, ex, request);
			} else {// JSON格式返回
				try {
					PrintWriter writer = response.getWriter();
					writer.write(ex.getMessage());
					writer.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;

			}
		} else {
			return null;
		}
	}

}
